<template>
  <div>
    <el-form ref="formRef" label-width="100" :model="formData" :rules="rules">
      <el-tabs v-model="tabs" @tab-change="changeTab">
        <el-tab-pane label="基础信息" name="1">
          <div class="w-500px">
            <el-form-item label="所属区域" prop="region">
              <el-cascader :props="cascaderProps" style="width: 300px" v-model="formData.region" :options="region"></el-cascader>
            </el-form-item>
            <el-form-item label="经度">
              <div>
                <el-input-number v-model="formData.longitude" :min="0" :max="180" :precision="6"></el-input-number>
              </div>
            </el-form-item>
            <el-form-item label="纬度">
              <div>
                <el-input-number v-model="formData.latitude" :min="0" :max="90" :precision="6"></el-input-number>
              </div>
            </el-form-item>
            <el-form-item label="选取地址">
              <el-button :icon="Compass" size="small" type="success" @click="chooseLocation">选取坐标地址</el-button>
            </el-form-item>
            <el-form-item label="楼盘名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入楼盘名称"></el-input>
              <!-- <el-button class="mt-10px" @click="chooseLouName">选取楼盘</el-button> -->
            </el-form-item>
            <el-form-item label="排序值">
              <el-input-number v-model="formData.sort" :precision="0" :min="1" :max="100000000"></el-input-number>
            </el-form-item>
            <el-form-item label="是否上架">
              <el-switch
                v-model="formData.grounding"
                active-text="上架"
                inactive-text="下架"
                :active-value="1"
                :inactive-value="2"
              ></el-switch>
            </el-form-item>
            <el-form-item label="楼盘封面" prop="cover">
              <ChooseFile fileType="image" v-model:url="formData.cover"></ChooseFile>
            </el-form-item>
            <el-form-item label="最小户型面积">
              <el-input-number v-model="formData.minArea" :min="0" :max="1000" class="mr-10px"></el-input-number>m²
            </el-form-item>
            <el-form-item label="最大户型面积">
              <el-input-number v-model="formData.maxArea" :min="0" :max="1000" class="mr-10px"></el-input-number>m²
            </el-form-item>
            <el-form-item label="产权年限" prop="years">
              <el-input v-model="formData.years" placeholder="请输入产权年限"></el-input>
            </el-form-item>
            <el-form-item label="参考价">
              <el-input-number
                placeholder="售价待定"
                :min="0"
                :max="99999999"
                :precision="0"
                class="mr-10px"
                v-model="formData.referencePrice"
              ></el-input-number
              >元/m²
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="formData.address" placeholder="请填写详细地址"></el-input>
            </el-form-item>
            <div class="w-1/1">
              <el-form-item label="开发商" prop="developer">
                <el-input v-model="formData.developer" placeholder="暂无资料"></el-input>
              </el-form-item>
              <el-form-item label="装修情况" prop="furnish">
                <el-input v-model="formData.furnish" placeholder="暂无资料"></el-input>
              </el-form-item>
              <el-form-item label="物业用途" prop="propertyUse">
                <el-select v-model="formData.propertyUse" multiple clearable class="w-1/1" placeholder="请选择物业用途">
                  <el-option v-for="(p, index) in propertyList" :key="index" :value="p.statusCode" :label="p.name"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="销售信息" name="2">
          <el-form-item label="销售状态" prop="status">
            <el-select v-model="formData.status">
              <el-option v-for="p in sellStatus" :key="p.statusCode" :value="p.statusCode" :label="p.name"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开盘时间" prop="openTime">
            <el-date-picker v-model="formData.openTime" placeholder="开盘时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="交房时间" prop="getRoomTime">
            <el-date-picker v-model="formData.getRoomTime" placeholder="交房时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="400电话">
            <el-input :disabled="true" v-model="formData.sellPhone"></el-input>
          </el-form-item>
          <el-form-item label="预售许可证" prop="license">
            <el-input v-model="formData.license" placeholder="暂无资料"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="小区规划" name="3">
          <el-form-item label="占地面积">
            <el-input-number
              v-model="formData.floorArea"
              :precision="2"
              :min="0"
              :max="100000000"
              placeholder="暂无资料"
            ></el-input-number
            ><span class="ml-10px">m²</span>
          </el-form-item>
          <el-form-item label="建筑面积">
            <el-input-number
              v-model="formData.buildArea"
              :precision="2"
              :min="0"
              :max="100000000"
              placeholder="暂无资料"
            ></el-input-number
            ><span class="ml-10px">m²</span>
          </el-form-item>
          <el-form-item label="楼栋总数">
            <el-input-number :min="0" :max="10000000" v-model="formData.buildNum" placeholder="暂无资料"></el-input-number
            ><span class="ml-10px">栋</span>
          </el-form-item>
          <el-form-item label="容积率">
            <el-input-number
              v-model="formData.volumeRate"
              :precision="2"
              :min="0"
              :max="100"
              placeholder="暂无资料"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="绿化率">
            <el-input-number v-model="formData.greeningRate" :min="0" :max="100" placeholder="暂无资料"></el-input-number
            ><span class="ml-10px">%</span>
          </el-form-item>
          <el-form-item label="规划用户">
            <el-input v-model="formData.userNum" placeholder="暂无资料"></el-input>
          </el-form-item>
          <el-form-item label="停车位">
            <el-input v-model="formData.parkingSpace" placeholder="暂无资料"></el-input>
          </el-form-item>
          <el-form-item label="物业费" prop="propertyCost">
            <el-input v-model="formData.propertyCost" placeholder="暂无资料"></el-input>
          </el-form-item>
          <el-form-item label="物业公司" prop="propertyCompany">
            <el-input v-model="formData.propertyCompany" placeholder="暂无资料"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="4" label="标签设置">
          <el-form-item label="楼盘标签" prop="tag">
            <el-select v-model="formData.tag" multiple class="w-1/1">
              <el-option v-for="(p, index) in tagList" :key="index" :value="p.id" :label="p.name">
                <span>{{ p.name }}</span
                ><span v-if="p.asSearch">(搜索)</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="楼盘特色">
            <el-select v-model="formData.tese" multiple class="w-1/1">
              <el-option v-for="p in teseList" :key="p.id" :value="p.id" :label="p.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="户型选择" prop="roomType">
            <el-select v-model="formData.roomType" multiple class="w-1/1">
              <el-option :value="p.id" v-for="(p, index) in roomList" :key="index" :label="p.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排行">
            <el-select v-model="formData.disadvantage" multiple class="w-1/1">
              <el-option :value="p.id" v-for="(p, index) in disList" :key="index" :label="p.name"></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <map-choose ref="mapRef" @select="getSelect"></map-choose>
  </div>
</template>

<script setup lang="ts">
import { CascaderProps, FormInstance, FormRules, TabPaneName } from "element-plus";
import { LouPan } from "@/api/interface/loupan";
import { ref, onBeforeMount } from "vue";
import { GetRegionByAccount } from "@/api/modules/account";
import { Compass } from "@element-plus/icons-vue";
import mapChoose from "@/components/mapChoose/index.vue";
import { findOptionById } from "@/utils/index";
import { Region } from "@/api/interface/region";
import { getSellList } from "@/api/modules/sellStatus";
import { getPropertyList as getPropertyListApi } from "@/api/modules/property";
import { getTagList as getTagListApi } from "@/api/modules/tag";
import { getDisList as getDisListApi } from "@/api/modules/dis";
import { getRoomTypeList } from "@/api/modules/room";
import { createLouPan, getInfo, editLouPan } from "@/api/modules/loupan";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getCity } from "@/api/modules/map";
import { list } from "@/api/modules/tese";
import ChooseFile from "@/components/ChooseFile/index.vue";

const router = useRouter();

const route = useRoute();

// ---当前选择的手机类型
const phoneType = ref(0); // 0表示大陆手机 1表示转接
const zhuan = ref("");

// ----获取户型
const roomList = ref();
const getRoomList = async () => {
  const { data } = await getRoomTypeList();
  roomList.value = data;
};

// -----获取不利因素
const disList = ref();
const getDisList = async () => {
  const { data } = await getDisListApi();
  disList.value = data;
};

// -----获取biaoqian
const tagList = ref();
const getTagList = async () => {
  const { data } = await getTagListApi({ pageNum: 1, pageSize: 9999, asSearch: -1 });
  tagList.value = (data as any).list.sort((a: any, b: any) => b.asSearch - a.asSearch);
};

// ----物业用途选择
const propertyList = ref();
const getpropertyList = async () => {
  const { data } = await getPropertyListApi();
  propertyList.value = data;
};

// ----销售状态选择
const sellStatus = ref();
const getSellStatus = async () => {
  const { data } = await getSellList();
  sellStatus.value = data;
};

// ----标签页配置
const tabs = ref("1");

const changeTab = (name: TabPaneName) => {
  tabs.value = name as string;
};

const initData: LouPan.Base = {
  nameId: 0,
  name: "",
  referencePrice: undefined,
  grounding: 1,
  sort: 1,
  cover: "",
  openTime: "",
  region: 0,
  address: "",
  location: "",
  longitude: 0,
  latitude: 0,
  maxArea: 0,
  minArea: 0,
  years: "",
  status: 1,
  getRoomTime: "",
  developer: "",
  sellPhone: "",
  license: "",
  floorArea: undefined,
  buildArea: undefined,
  buildNum: undefined,
  userNum: undefined,
  parkingSpace: undefined,
  volumeRate: undefined,
  greeningRate: undefined,
  propertyCost: "",
  propertyCompany: "",
  furnish: "",
  propertyUse: [],
  tag: [],
  disadvantage: [],
  roomType: [],
  tese: []
};

// ----校验规则
const validRegion = (rule: any, value: any, callback: any) => {
  if (value === 0) return callback(new Error("区域不可为空"));
  callback();
};

const formData = ref<LouPan.Base>(JSON.parse(JSON.stringify(initData)) as LouPan.Base);

// ---户型最小面积不可超过户型最大面积
const maxAndMin = (rule: any, value: any, callback: any) => {
  if (formData.value.maxArea < formData.value.minArea) return callback(new Error("户型最小面积不可超过户型最大面积"));
  callback();
};

const rules: FormRules = {
  name: [
    { required: true, message: "不可为空", trigger: "blur" },
    { max: 20, min: 1, message: "字数为1-20个", trigger: "blur" }
  ],
  region: [{ required: true, validator: validRegion, trigger: "blur" }],
  cover: [{ required: true, message: "封面不可为空", trigger: "blur" }],
  years: [
    { required: true, message: "产权不可为空", trigger: "blur" },
    { message: "字数为2-50字", max: 50, min: 2 }
  ],
  address: [
    { required: true, message: "地址不可为空", trigger: "blur" },
    { min: 1, max: 60, message: "地址字数为1-60字" }
  ],
  maxArea: [{ required: true, validator: maxAndMin, trigger: "blur" }],
  minArea: [{ required: true, validator: maxAndMin, trigger: "blur" }],
  developer: [{ min: 0, max: 20, message: "字数0-20个字" }],
  furnish: [{ min: 0, max: 40, message: "字数0-40个字" }],
  propertyUse: [{ required: true, message: "物业用途不可为空", type: "array", trigger: "blur" }],
  // openTime: [{ message: "开盘时间不可为空", type: "date", trigger: "blur" }],
  // getRoomTime: [{ message: "交房时间不可为空", type: "date", trigger: "blur" }],
  // sellPhone: [{ required: true, message: "销售电话不可为空", max: 20, min: 1, trigger: "blur" }],
  license: [{ max: 30, message: "字数不可超过30个字", trigger: "blur" }],
  propertyCost: [{ max: 30, message: "字数不可超过30个字", trigger: "blur" }],
  propertyCompany: [{ max: 30, message: "字数不可超过30个字", trigger: "blur" }],
  tag: [{ required: true, message: "标签不可为空", trigger: "blur", type: "array" }],
  roomType: [{ required: true, message: "户型不可为空", trigger: "blur", type: "array" }]
};

const formRef = ref<FormInstance>();

// ------------获取选择的地区
const region = ref();
const mapRef = ref<InstanceType<typeof mapChoose> | null>();

const chooseLocation = async () => {
  if (formData.value.region === 0) return;
  const res = findOptionById(region.value as Region.Option[], formData.value.region);
  const { data } = await getCity({ id: res?.id });
  if (res) {
    mapRef.value?.open([data, res]);
  }
};

const cascaderProps: CascaderProps = {
  children: "districts",
  label: "name",
  value: "id",
  emitPath: false
};

const getRegion = async () => {
  const { data } = await GetRegionByAccount();
  region.value = data;
};

//获取楼盘选择的地址
const getSelect = (val: any) => {
  console.log(val);
  formData.value.address = val.address;
  formData.value.location = val.location;
  const list = val.location.split(",").map((e: string) => parseFloat(e));
  formData.value.longitude = list[0];
  formData.value.latitude = list[1];
  formData.value.name = val.name;
};

// 提交
const submit = () => {
  formRef.value?.validate(async valid => {
    console.log(formData.value);
    console.log(valid);
    if (valid) {
      console.log("hhhhhh");
      try {
        const data = JSON.parse(JSON.stringify(formData.value));
        formData.value.openTime = new Date(data.openTime).getTime();
        formData.value.getRoomTime = new Date(data.getRoomTime).getTime();
        formData.value.location = [formData.value.longitude, formData.value.latitude].join(",");
        if (phoneType.value === 1) {
          formData.value.sellPhone = formData.value.sellPhone + "," + zhuan.value;
        }
        if (!route.query.id) {
          await createLouPan(formData.value);
        } else {
          formData.value.id = parseInt(route.query.id as string);
          await editLouPan(formData.value);
        }
        ElMessage.success("成功");
        router.back();
      } catch (error) {
        console.log(1111, error);
      }
    }
  });
};

const teseList = ref();
const getTeseList = async () => {
  const { data } = await list();
  teseList.value = data;
};

const initFormData = (res: any) => {
  const data = JSON.parse(JSON.stringify(res));
  // formData.value.nameId = data.louPanName.id;
  formData.value.sort = data.sort;
  formData.value.region = data.region;
  formData.value.grounding = data.grounding;
  formData.value.name = data.name;
  formData.value.maxArea = data.maxArea;
  formData.value.minArea = data.minArea;
  formData.value.address = data.address;
  formData.value.longitude = data.longitude;
  formData.value.latitude = data.latitude;
  formData.value.location = data.location;
  formData.value.cover = data.cover;
  formData.value.referencePrice = data.reference_price === 0 ? "售价待定" : data.reference_price;
  formData.value.years = data.years;
  formData.value.developer = data.sellLouPanInfo.developer;
  formData.value.furnish = data.furnish;
  formData.value.propertyUse = data.property.map((e: any) => e.id);
  formData.value.status = data.sell_status;
  if (data.sellLouPanInfo.open_time === 0) {
    formData.value.openTime = undefined;
  } else {
    formData.value.openTime = new Date(data.sellLouPanInfo.open_time).toISOString();
  }
  if (data.sellLouPanInfo.getRoomTime === 0) {
    formData.value.getRoomTime = undefined;
  } else {
    formData.value.getRoomTime = formData.value.getRoomTime = new Date(data.sellLouPanInfo.getRoomTime).toISOString();
  }
  if (data.sellLouPanInfo.sellPhone) {
    if (data.sellLouPanInfo.sellPhone.includes(",")) {
      phoneType.value = 1;
      const phones = data.sellLouPanInfo.sellPhone.split(",");
      formData.value.sellPhone = phones[0];
      zhuan.value = phones[1];
    } else {
      formData.value.sellPhone = data.sellLouPanInfo.sellPhone;
    }
  }

  formData.value.license = data.sellLouPanInfo.license;
  formData.value.floorArea = data.lou_pan_area.floorArea === 0 ? undefined : data.lou_pan_area.floorArea;
  formData.value.buildArea = data.lou_pan_area.buildArea === 0 ? undefined : data.lou_pan_area.buildArea;
  formData.value.userNum = data.lou_pan_area.userNum === 0 ? undefined : data.lou_pan_area.userNum;
  formData.value.buildNum = data.lou_pan_area.buildNum === 0 ? undefined : data.lou_pan_area.buildNum;
  formData.value.parkingSpace = data.lou_pan_area.parkingSpace === 0 ? undefined : data.lou_pan_area.parkingSpace;
  formData.value.volumeRate = data.lou_pan_area.volumeRate === 0 ? undefined : data.lou_pan_area.volumeRate;
  formData.value.greeningRate = data.lou_pan_area.greeningRate === 0 ? undefined : data.lou_pan_area.greeningRate;
  formData.value.propertyCost = data.lou_pan_area.propertyCost;
  formData.value.propertyCompany = data.lou_pan_area.propertyCompany;
  formData.value.tag = data.tags.map((e: any) => e.id);
  formData.value.roomType = data.room_type.map((e: any) => e.id);
  formData.value.tese = data.tese.map((e: any) => e.id);
  formData.value.disadvantage = data.disadvantage.map((e: any) => e.id);
};

onBeforeMount(async () => {
  await Promise.all([getRegion(), getSellStatus(), getpropertyList(), getTagList(), getDisList(), getRoomList(), getTeseList()]);
  if (route.query.id) {
    const { data } = await getInfo(parseInt(route.query.id as string));
    initFormData(data);
  }
});
</script>

<style></style>
